package com.miszczu.dziennik;

import java.util.Collection;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.miszczu.bo.UsersBo;
import com.miszczu.dao.UsersDao;
import com.miszczu.utils.PathFinder;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	
	
	private String getAuthority() {
		
		String userAuth = null;
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		@SuppressWarnings("unchecked")
		Collection<GrantedAuthority> authorities = (Collection<GrantedAuthority>) auth.getAuthorities();
		
		for(GrantedAuthority authority : authorities) {
			// zakladamy ze user ma tylko jedno authority wiec zwracamy tylko pierwszy element kolekcji:
			userAuth = authority.getAuthority();
			break;
		}
		
		return userAuth;
	}
	
	@RequestMapping(value = "/auth/welcome", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		
		return "parent_welcome";
	}
	
	@RequestMapping(value = "/teacher/welcome", method = RequestMethod.GET)
	public String teacherHome(Locale locale, Model model) {
		
		return "teacher_welcome";
	}
	
	@RequestMapping(value = "/admin/welcome", method = RequestMethod.GET)
	public String adminHome(Locale locale, Model model) {
		
		return "admin_welcome";
	}
	
	@RequestMapping(value = "/logged", method = RequestMethod.GET)
	public String logged(Locale locale, Model model) {
		
		String authority = this.getAuthority();
		
		model.addAttribute("authority", PathFinder.getPathFromRole(authority));
		
		return "logged";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Locale locale, Model model) {
		
		return "login";
	}
	
	@RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
	public String loginFailed(Locale locale, Model model) {
		
		return "loginfailed";
	}
	
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public String info(Locale locale, Model model) {
		
		return "info";
	}
	
}
